import { createRouter, createWebHashHistory } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import Dashboard from '../views/Dashboard.vue'
import Users from '../views/user/Users.vue'
import Roles from '../views/user/Roles.vue'
import Permissions from '../views/user/Permissions.vue'
import Settings from '../views/Settings.vue'
import Login from '../views/Login.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { 
      requiresAuth: false,
      layout: 'empty' 
    }
  },
  {
    path: '/',
    name: 'Dashboard',
    component: Dashboard,
    meta: { 
      requiresAuth: true,
      layout: 'default' 
    }
  },
  {
    path: '/users',
    name: 'Users',
    component: Users,
    meta: { 
      requiresAuth: true,
      layout: 'default' 
    }
  },
  {
    path: '/roles',
    name: 'Roles',
    component: Roles,
    meta: { 
      requiresAuth: true,
      layout: 'default' 
    }
  },
  {
    path: '/permissions',
    name: 'Permissions',
    component: Permissions,
    meta: { 
      requiresAuth: true,
      layout: 'default' 
    }
  },
  {
    path: '/settings',
    name: 'Settings',
    component: Settings,
    meta: { 
      requiresAuth: true,
      layout: 'default' 
    }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  const isAuthenticated = await authStore.checkAuth()

  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else if (to.path === '/login' && isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router
